import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import LocalOutlierFactor
# 测试代码提交

# 读取数据，并删去日期这些非浮点数类型的列
file_path = r'000001.SZ.csv'
dataset = pd.read_csv(file_path)
dataset = dataset.drop(columns = ["trade_date", "date"])
print(dataset.head())

# dataset_t = dataset.transpose()
# print(dataset_t.head())

X = dataset.values
print(X)

# for column in dataset.columns:
#     print("'"+column+"'")

# 利用相关模型找出异常的数据并进行删除
lof = LocalOutlierFactor(contamination=0.01)
X_lof = lof.fit_predict(X)
print('原始数据条数： ' + str(X.shape[0]))
X = X[X_lof == 1]
print('删除异常数据后的数据条数： ' + str(X.shape[0]))


# 选取想要可视化的参数
# selected_columns = ['close', 'open', 'high', 'low', 'pre_close', 'change', 'pct_chg', 'vol', 'amount', 'MACD',
#                     'DEA', 'Histogram', 'MA5', 'MA10', 'RSI', 'MOM', 'EMA12', 'EMA26', 'open-close', 'high-low']

selected_columns = ['close', 'open', 'high', 'low', 'pre_close', 'MA5', 'MA10', 'RSI', 'EMA12', 'EMA26']

df_lof = pd.DataFrame(data = X,columns = dataset.columns)

upper_all = []

# 按Fmark类别进行分组，目的是观测这4组之间数据的差异
df_typ1 = df_lof[df_lof['Fmark']==1]
df_typ2 = df_lof[df_lof['Fmark']==-1]
df_typ3 = df_lof[df_lof['Fmark']==2]
df_typ4 = df_lof[df_lof['Fmark']==-2]

upper_typ1 = []
upper_typ2 = []
upper_typ3 = []
upper_typ4 = []
for column in selected_columns:
    upper_all.append(df_lof[column].describe()['75%'])
    upper_typ1.append(df_typ1[column].describe()['75%'])
    upper_typ2.append(df_typ2[column].describe()['75%'])
    upper_typ3.append(df_typ3[column].describe()['75%'])
    upper_typ4.append(df_typ4[column].describe()['75%'])

# 删去第一个数据
upper_all = upper_all[1:]
upper_typ1 = upper_typ1[1:]
upper_typ2 = upper_typ2[1:]
upper_typ3 = upper_typ3[1:]
upper_typ4 = upper_typ4[1:]

# 并且把现在第一个数据的值也放到最后一个地方，确保画出来是一个首尾连接的闭合图形
upper_all.append(upper_all[0])
upper_typ1.append(upper_typ1[0])
upper_typ2.append(upper_typ2[0])
upper_typ3.append(upper_typ3[0])
upper_typ4.append(upper_typ4[0])

# 绘制图所需相关数据，并可视化结果
angles = np.linspace(0, 2*np.pi, len(selected_columns)-1, endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
plt.polar(angles, upper_all, 'bo-', linewidth=1, label=f"type = all")
plt.polar(angles, upper_typ1, 'ro-', linewidth=1, label=f"type = 1")
plt.polar(angles, upper_typ2, 'go-', linewidth=1, label=f"type = -1")
plt.polar(angles, upper_typ3, 'co-', linewidth=1, label=f"type = 2")
plt.polar(angles, upper_typ4, 'mo-', linewidth=1, label=f"type = -2")
plt.legend(loc='best')
plt.thetagrids(angles * 180/np.pi, selected_columns)
plt.show()

